package com.ssm.blog.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.blog.pojo.Blog;
import com.ssm.blog.pojo.Category;
import com.ssm.blog.pojo.criteria.BlogCriteria;
import com.ssm.blog.service.BlogService;
import com.ssm.blog.service.CategoryService;
import com.ssm.blog.util.Funcs;
import com.ssm.blog.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/blog.html")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping(params = "act=edit")
    @ResponseBody
    public Map<String, Object> edit(Blog blog) {
        if (blog.getId() == null) {
            //从session中获取user的信息,后面写完登录再改
            blog.setUserId(1);
            blogService.addBlog(blog);
        } else {
            //
            //修改
        }
        return JsonUtil.getSuccessMessage("编辑成功", null);
    }


    @RequestMapping(params = "act=get")
    public ModelAndView getBlog(Integer id) {
        Blog blog = null;
        if (id != null) {
            blog = blogService.getBlogById(id);
        }
        return new ModelAndView("blog_edit", "blog", blog);
    }

    @RequestMapping(params = "act=list")
    @ResponseBody
    public Map<String, Object> list(BlogCriteria criteria, int page, int rows) {
        PageInfo<Blog> pageInfo = blogService.getBlogList(criteria, page, rows);
        return JsonUtil.getDatagridPagerResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @Autowired
    private CategoryService categoryService;

    //查询所有分类的列表
    @RequestMapping(params = "act=category")
    @ResponseBody
    public List<Category> category() {
        List<Category> categories = categoryService.getCategoryList(null);
        return categories;
    }

    @Value("${BLOG_IMAGE_DIR}")
    private String BLOG_IMAGE_DIR;
    @Value("${BLOG_IMAGE_URL}")
    private String BLOG_IMAGE_URL;

    @RequestMapping(params = "act=upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        try {
            String newFileName = Funcs.uploadFile(file, BLOG_IMAGE_DIR);
            return "{\"error\":0,\"url\":\"" + BLOG_IMAGE_URL + newFileName + "\"}";
        } catch (IOException e) {
            e.printStackTrace();
            return "{\"error\":1}";
        }
    }
}
